package org.czx.datactruct.six;

import org.czx.datactruct.fifth.StackInterface;

import java.util.EmptyStackException;
import java.util.Vector;

/**
 * @author czx
 * @date 2020/9/11 16:30
 */
public class VectorStack<T> implements StackInterface<T> {
    private Vector<T> stack;      // Last elements is the top entry in stack
    private boolean initialized = false;
    private static final int DEFAULT_CAPACITY = 50;
    private static final int MAX_CAPACITY = 10000;

    /**
     * Creates an empty stack whose initial capacity is 50.
     */
    public VectorStack() {
        this(DEFAULT_CAPACITY);
    }

    /**
     * Creates an empty stack having a given capacity.
     *
     * @param initialCapacity The integer capacity desired.
     */
    public VectorStack(int initialCapacity) {
        checkCapacity(initialCapacity);
        stack = new Vector<>(initialCapacity);
        initialized = true;
    }

    @Override
    public void push(T newEntry) {
        checkInitialization();
        stack.add(newEntry);
    }

    @Override
    public T pop() {
        checkInitialization();
        if (isEmpty())
            throw new EmptyStackException();
        else
            return stack.remove(stack.size() - 1);
    }

    @Override
    public T peek() {
        checkInitialization();
        if (isEmpty())
            throw new EmptyStackException();
        else
            return stack.lastElement();
    }

    @Override
    public boolean isEmpty() {
        return stack.isEmpty();
    }

    @Override
    public void clear() {
        stack.clear();
    }

    // Throws an exception if this object is not initialized.
    private void checkInitialization() {
        if (!initialized)
            throw new SecurityException("ArrayStack object is corrupt.");
    }

    // Throws an exception if the client requests a capacity that is too large.
    private void checkCapacity(int initialCapacity) {
        if (initialCapacity > MAX_CAPACITY)
            throw new IllegalStateException("Attempt to create a stack " +
                    "whose capacity exceeds " +
                    "allowed maximum of ." + MAX_CAPACITY);
    }
}
